package com.dyz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dyz.domain.DTO.SysUserDTO;
import com.dyz.domain.SysUser;
import com.dyz.domain.SysUserRole;
import com.dyz.domain.VO.SysUserVo;
import com.dyz.mapper.SysUserMapper;
import com.dyz.model.Result;
import com.dyz.service.ISysUserRoleService;
import com.dyz.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 平台用户 服务实现类
 * </p>
 *
 * @author dyz
 * @since 2025-04-19
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Resource
    private ISysUserRoleService sysUserRoleService;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public Result<?> findUsers(Page<SysUser> page, String username, String mobile) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysUser> userPage = page(page, new LambdaQueryWrapper<SysUser>().like(
                !StringUtils.isEmpty(username),
                SysUser::getUsername, username
                ).like(!StringUtils.isEmpty(mobile),
                SysUser::getMobile, mobile
                )
        );
        List<SysUser> records = userPage.getRecords();
        if(!CollectionUtils.isEmpty(records)){
            for (SysUser record : records) {
                List<SysUserRole> userRoles = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, record.getId()));
                if(!CollectionUtils.isEmpty(userRoles)){
                    record.setStrRoleIds(userRoles.stream().map(sysUserRole -> sysUserRole.getRoleId().toString()).collect(Collectors.joining(",")));
                }
            }
        }
        return Result.success(userPage);
    }

    @Override
    @Transactional
    public Result<?> addUser(SysUserDTO sysUserDTO) {
        SysUser sysUser = new SysUser();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(sysUserDTO.getPassword());
        sysUserDTO.setPassword(password);
        //将sysUserDTO中的属性拷贝到sysUser中
        BeanUtil.copyProperties(sysUserDTO, sysUser);
        int row = sysUserMapper.insert(sysUser);
        boolean success = false;
        // 保存用户角色的权限
        if(!StringUtils.isEmpty(sysUserDTO.getStrRoleIds())&&row>0){
            String[] roleIds = sysUserDTO.getStrRoleIds().split(",");
            for (String roleId : roleIds) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(Long.valueOf(roleId));
                sysUserRole.setUserId(sysUser.getId());
               success= sysUserRoleService.save(sysUserRole);
            }
        }
        return success?Result.success("添加成功"):Result.fail("添加失败");
    }

    @Override
    @Transactional
    public Result<?> updateUser(SysUserDTO sysUserDTO) {
        SysUser sysUser = new SysUser();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(sysUserDTO.getPassword());
        sysUserDTO.setPassword(password);
        //将sysUserDTO中的属性拷贝到sysUser中
        BeanUtil.copyProperties(sysUserDTO, sysUser);
        boolean update = this.saveOrUpdate(sysUser);
        boolean success = false;
        // 保存用户角色的权限
        if(!StringUtils.isEmpty(sysUserDTO.getStrRoleIds())&&update){
            // 先删除用户角色的权限
            boolean remove = sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, sysUser.getId()));
            if(remove){
                // 再保存用户角色的权限
                String[] roleIds = sysUserDTO.getStrRoleIds().split(",");
                for (String roleId : roleIds) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(Long.valueOf(roleId));
                    sysUserRole.setUserId(sysUser.getId());
                    success= sysUserRoleService.save(sysUserRole);
                }
            }
        }
        return success?Result.success("添加成功"):Result.fail("添加失败");
    }

    @Override
    @Transactional
    public Result<?> deleteUserByIds(String userIds) {
        if(StringUtils.isEmpty(userIds)){
            return Result.fail("删除失败");
        }
        String[] split = userIds.split(",");
        ArrayList<Long> userIdsList = new ArrayList<>();
        for (String s : split) {
            userIdsList.add(Long.valueOf(s));
        }
        boolean remove = removeByIds(userIdsList);
        if(remove){
            //删除用户角色的权限
            remove=sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, userIdsList));
        }
        return remove?Result.success("删除成功"):Result.fail("删除失败");
    }

    @Override
    public Result<?> getUserById(Long userId) {
        SysUser sysUser = new SysUser();
        SysUserVo sysUserVo = new SysUserVo();
        if(userId!=null){
             sysUser = getById(userId);
            if(sysUser!=null){
                List<SysUserRole> userRoles = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
                if(!CollectionUtils.isEmpty(userRoles)){
                    sysUser.setStrRoleIds(userRoles.stream().map(sysUserRole -> sysUserRole.getRoleId().toString()).collect(Collectors.joining(",")));
                }
            }
        }
        BeanUtil.copyProperties(sysUser, sysUserVo);
        return Result.success(sysUserVo);
    }
}
